<template>
  <!-- 绑定手机 -->
  <Form
    class="xtx-form"
    :validation-schema="schema"
    v-slot="{ errors }"
    autocomplete="off"
    ref="formCom"
  >
    <div class="user-info">
      <img
        src="http://qzapp.qlogo.cn/qzapp/101941968/57C7969540F9D3532451374AA127EE5B/50"
        alt=""
      />
      <p>Hi，Jerry 欢迎来稿定，完成绑定后可以QQ账号一键登录哦</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          v-model="form.mobile"
          name="mobile"
          type="text"
          class="input"
          placeholder="绑定的手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          v-model="form.code"
          name="code"
          type="text"
          class="input"
          placeholder="短信验证码"
        />
        <span @click="send(formCom)" class="code">
          {{ time === 0 ? '发送验证码' : `${time}秒后发送` }}</span
        >
      </div>
      <div v-if="errors.code" class="error">{{ errors.code }}</div>
    </div>
    <a @click="submit(formCom)" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { ref, reactive, onUnmounted } from 'vue'
import { Field, Form } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
import QC from 'qc'
import { message } from '../../../components/library/message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Field, Form },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // 1. 准备下信息：unionId(openId) qq头像 昵称
    // 2.完成表单校验
    // 3.发送验证码（校验，定义api，调用，完成倒计时）
    // 4.进行绑定（绑定成功就是登录成功）
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      QC.api('get_user_info').success((res) => {
        avatar.value = res.data.figureurl_qq_1
        nickname.value = res.data.nickname
      })
    }

    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null
    })

    // 发送短信验证码
    // pause 暂停 resume 开始
    // useIntervalFn(回调函数,执行间隔,是否立即开启)
    const formCom = ref(null)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      { immediate: false }
    )
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    // 1.1 绑定发送验证码按钮点击事件
    // 1.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
    // 1.3 如果失败，失败的校验样式显示出来
    const send = async (formEl) => {
      const valid = formEl.validate()
      if (valid) {
        if (form.mobile) {
          // 通过倒计时没有结束直接退出
          if (time.value !== 0) return
          try {
            // 发送短信验证码
            await userQQBindCode(form.mobile)
            // 发送成功后提示
            message({ type: 'success', message: '发送成功' })
            // 重置倒计时秒数
            time.value = 60
            // 启动定时器
            resume()
          } catch (e) {
            message({
              type: 'error',
              message: e.response.data.message || '登录失败'
            })
          }
        }
      }
    }

    // 立即绑定
    const store = useStore()
    const router = useRouter()
    const submit = async (formEl) => {
      // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
      const valid = formEl.validate()
      if (valid) {
        // 发送请求
        userQQBindLogin({ unionId: props.unionId, ...form })
          .then((data) => {
            // 实现和之前登录一样
            // 1.存储信息
            const { id, avatar, nickname, account, mobile, token } = data.result
            store.commit('user/setUser', {
              id,
              avatar,
              nickname,
              account,
              mobile,
              token
            })
            // 2.跳转
            router.push(store.state.user.redirectUrl)
            // 3.提示
            message({ type: 'success', message: 'QQ绑定成功' })
          })
          .catch((e) => {
            message({ type: 'success', message: '绑定失败' })
          })
      }
    }
    return { formCom, send, nickname, avatar, schema, time, submit, form }
  }
}
</script>
<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background-color: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 35px;
  img {
    background-color: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
